 ///
 /// @file    client.c
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2022-07-12 16:08:45
 ///
#define _XOPEN_SOURCE
#include "client_gets_file.h" 
#include "client_puts_file.h" 
#include <head.h>

int passwdCheck(int peerfd);

void logincheck(int clientfd) {
     char sendbuf[1024] = {0};
     char recvbuf[1024] = {0};

     fgets(sendbuf, sizeof(sendbuf), stdin);
     char *pchar = strchr(sendbuf, '\n');
     if(pchar!=NULL) *pchar = '\0';
     sendbuf[1023]='\0';
     
     //puts(sendbuf);
     send(clientfd, sendbuf, strlen(sendbuf), 0);
     bzero(sendbuf, 1024);
     bzero(recvbuf, 1024);
     puts("waiting salt...");
     recv(clientfd, recvbuf, 12, 0);
     puts("password please: ");

     fgets(sendbuf, sizeof(sendbuf), stdin);
     pchar = strchr(sendbuf, '\n');
     if(pchar!=NULL) *pchar = '\0';
     sendbuf[1023]='\0';

     crypt(sendbuf, recvbuf);
     send(clientfd, crypt(sendbuf, recvbuf), strlen(crypt(sendbuf, recvbuf)), 0);
     return ;
}

int main(int argc,char *argv[])
{
	//0. 创建套接字
	int clientfd = socket(AF_INET, SOCK_STREAM, 0);
	ERROR_CHECK(clientfd, -1, "socket");

	printf("sizeof(struct sockaddr):%ld\n", sizeof(struct sockaddr));
	printf("sizeof(struct sockaddr_in):%ld\n", sizeof(struct sockaddr_in));

	//1. 设置服务器的网络地址
	struct sockaddr_in serverAddr;
	memset(&serverAddr, 0, sizeof(serverAddr));

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(atoi(argv[2]));
	serverAddr.sin_addr.s_addr = inet_addr(argv[1]);

	int ret = connect(clientfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
	ERROR_CHECK(ret, -1, "connect");
	printf("conn has connected\n");
    //logincheck(clientfd);
    int flag = 1;
    while(flag) flag = passwdCheck(clientfd);

    char sendbuf[1024] = {0};
    char recvbuf[1024] = {0};
    int retval = 0;
    while(1) {
        bzero(sendbuf, 1024);
        bzero(recvbuf, 1024);
        fgets(sendbuf, sizeof(sendbuf), stdin);
        char *pchar = strchr(sendbuf, '\n');
        if(pchar!=NULL)
            *pchar = '\0';
        sendbuf[1023]='\0';
        
        //puts(sendbuf);
        send(clientfd, sendbuf, strlen(sendbuf), 0);
        char tempbuff[5] = {0};
        strncpy(tempbuff, sendbuf, 4);
        tempbuff[4] = '\0';
        if(!strcmp("gets", tempbuff)) {
            recv_file(clientfd);
            continue;
        }
        else if(!strcmp("puts", tempbuff)) {
            char *findblank = strchr(sendbuf, ' ');
            recv(clientfd, recvbuf, sizeof(recvbuf), 0);
            transferfile(clientfd, findblank + 1);
            continue;
        }

        retval = recv(clientfd, recvbuf, sizeof(recvbuf), 0);
        if(retval == 0) break;
        printf("remote>> %s\n", recvbuf);
    }
	close(clientfd);
    
}
